<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>WebSocket</title>
</head>

<body class="bg-dark scroll-style">
<h1>Welcome!</h1>

<button onclick="connect()">连接</button>
<br/>
<button onclick="disconnect()">断开连接</button>
<br/>
<button onclick="send()">发送</button>

<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">

    const stompEndPoint = '/endpointWisely';
    const toPage = '/topic/message';
    const toUserPrefix = '/p2p';
    const toUserSuffix = '/msg';

    var stompClient;

    function connect() {
        var socket = new SockJS(stompEndPoint);
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            console.log(frame);
            // 订阅 topic 消息
            stompClient.subscribe(toPage, function (response) {
                console.log(response);
            });
            // 订阅 p2p 消息
            stompClient.subscribe(toUserPrefix + 'admin' + toUserSuffix, function (response) {
                console.log(response);
            });
        });
    }

    function disconnect() {
        if (null != stompClient) {
            stompClient.disconnect();
        }
    }

    function send() {
        var name = 'admin';
        stompClient.send('/ws/server/client', {}, JSON.stringify({'name': name}));
    }

    connect();

</script>

</body>

</html>
